<?php
// +----------------------------------------------------------------------
// | Author: 
// +----------------------------------------------------------------------

namespace app\wechat\controller;
/**
 * 个人中心控制器
 */
class UserController extends AuthController {
    private $model;
    public function _initialize() {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 个人中心首页
     */
    public function index(){
        $user_info = db("user")->where(array("id"=>$this->user_id))->find();
        $coupon_conut = db('user_coupon')->where(array("user_id"=>$this->user_id,'status'=>1))->count();
        $this->assign('coupon_conut',$coupon_conut);
        $this->assign("user_info",$user_info);
        return $this->fetch('index');
    }

    public function info(){
        $user_info = $this->model->find(['id'=>$this->user_id]);
        if(IS_POST){
            $data = [
                'id'=>$this->user_id,
                'surname'=>input('param.surname'),
                'sex'=>input('param.sex'),
                'mobile'=>input('param.mobile'),
                'address'=>input('param.address'),
                'car_number'=>input('param.car_number'),
            ];
            if($this->model->update($data) !== false){
                if(input('param.is_cart')){
                    $this->redirect('Order/cart');
                }else{
                    $this->success('保存成功',Url('User/index'));
                    exit;
                }
            }else{
                $this->error('保存失败，请重试');
            }
        }
        $this->assign("user_info",$user_info);
        return $this->fetch('info');
    }



    /**
     * 订单页面
     */
    public function order(){
        return $this->fetch('order');
    }


    /**
     * ajax获取订单列表
     */
    public function ajax_get_order_list(){
        $state = input('param.status');
        $inquire = input('param.inquire');
        switch ($state){
            case 'all':
                $where = array('user_id'=>$this->user_id);
                break;
            case '1'://还未支付
                $where = array('pay_status'=>0,'order_status'=>0,'user_id'=>$this->user_id);
                break;
            case '2'://进行中
                $where = "user_id = {$this->user_id} AND pay_status = 1 AND (order_status = 2 OR order_status = 0)";
                break;
            case '3'://已完成
                $where = array('pay_status'=>1,'order_status'=>4,'user_id'=>$this->user_id);
                break;
            case '4'://待评价
                $where = array('order_status'=>2,'user_id'=>$this->user_id);
                break;
            default:
                $where = array('user_id'=>$this->user_id);
                break;
        }

        if(!empty($inquire)){
            $where['order_sn'] = array('like',"%".$inquire."%");
        }
        //获取各种订单状态数量
        $order_list = db('order')->where($where)->order('add_time desc')->select();

        $order_html = "";
        
        if($order_list){
            $tmpl = '<li>
                 <a href="%s" style="display: block;">
                     <div class="orderlist_top">
                        <span>订单编号：%s</span>
                        <span>%s</span>
                     </div>
                     %s
                      <div class="order_amount">共%s件商品，实付：¥ %s</div>
                  </a>
                   %s
            </li>';

            $detail_tmpl =  '<div class="orderlist_content">
                               <div class="content_img"> <img src="%s" alt="" width="100%%"></div>
                               <div class="content_name">
                                     <p>%s</p>
                                     <p>%s</p>
                                     <p style="font-size: 12px;color: #ff5100;">%s</p>
                               </div>
                                    <div class="content_price">
                                        <p>¥ %s</p>
                                        <p class="quantity">x%s</p>
                                    </div>
                               </div>';




            foreach ($order_list as $order){
                $status_html = '';
                $detail_list = db('order_goods')
                    ->alias('a')
                    ->join('__GOODS__ b','a.goods_id = b.id')
                    ->field('a.*,b.image,b.cate_id')
                    ->where(array('a.order_id'=>$order['order_id']))
                    ->select();
                $detail_html = "";
                $zoj=0;
                $count=0;
                foreach ($detail_list as $detail){
                    $count_str = '';
                    if($order['pay_status'] == 1 && $order['order_status'] == 0){
                        $count = db('OrderGoods')->alias('g')
                            ->join('__ORDER__ o','o.order_id = g.order_id','LEFT')
                            ->where(['o.pay_status'=>1, 'o.order_status'=>0, 'o.add_time'=>['lt',$order['add_time']], 'g.cate_id'=>['like',"%{$detail['cate_id']}%"]])
                            ->count();
                        if($count > 0){
                            $count_str = str_replace('%',$count,$this->system_config['queue_number']);
                        }
                    }

                    $keys = explode('_',$detail['attr_key']);
                    $attr_value = db('goods_attr_value')->where(array("id"=>$keys[0]))->find();
                    $detail_html .=sprintf($detail_tmpl,
//                       U('order_detail',array('order_id'=>$order['order_id'])),
                        $detail['image'],
                        $detail['goods_name'],
                        $attr_value['value'],
                        $count_str,
                        $detail['price'],
                        $detail['goods_num']
                    );


                    $count += $detail['goods_num'];
                }
                if($order['pay_status']==0 && $order['order_status'] == 0){
                    $status_tmp = '<div class="orderlist_icon">
                          <span><a href="%s">去付款</a></span>
                          <span class="cancel_order" id="trigger2" data-id="%s"><a href="%s">取消订单</a></span>
                          </div>';
                    $url_name = "待付款";
                    $url = Url('Order/payCode',array('order_id'=>$order['order_id']));
                    $url2 = Url('Order/cancel',array('order_id'=>$order['order_id']));
                    $status_html =sprintf($status_tmp,
                        $url,
                        $order['order_id'],
                        $url2
                    );

                }else if($order['order_status']==2 || ($order['order_status'] == 0 && $order['pay_status'] == 1)){
                    $url_name = '进行中';
                }else if($order['order_status'] == 3){
                    $url_name = '已取消';
                }else if($order['order_status'] == 4){
                    $url_name = '已完成';
                }
                $order_html.=sprintf($tmpl,
                    '#',
//                    U('User/orderDetail',['order_id'=>$order['order_id']]),
                    $order['order_sn'],
                    $url_name,
                    $detail_html,
                    $count,
                    sprintf('%.2f',$order['order_amount']),
                    $status_html
                );
            }
        }else{
            $tmpl = '<li>
              <div class="emptyorder">
               <div><img src="../../../../../Public/home/images/empty_03.png" alt="" width="100%%"></div>
               <p>您还没有任何订单哦~</p>
              </div>
              </li>';
            $order_html.=sprintf($tmpl);
        }
        $this->success($order_html);
    }

    /**
     * 订单详情
     */
    public function orderDetail(){
        $order_id = input('param.order_id');
        $order = db('Order')
            ->alias('o')
            ->join('__REGION__ r','r.id = o.province or r.id = o.city or r.id = o.district','LEFT')
            ->join('__USER__ u','u.id = o.user_id','LEFT')
            ->field('o.*, group_concat(r.name SEPARATOR "") as region_address, u.nickname')
            ->where(['o.order_id'=>$order_id])
            ->find();
        if(empty($order)){
            $this->error('订单不存在！');
        }
        $button = "";
        if($order['pay_status'] ==0 && $order['order_status'] ==0){
            $order['status_str'] = '待付款';
            $button .= "<span data-url='".Url('Order/payCode',['order_id'=>$order['order_id']])."'>去付款</span>";
            $button .= "<span data-url='".Url('Order/cancel',['order_id'=>$order['order_id']])."'>取消订单</span>";
        }elseif($order['pay_status'] ==1 && $order['shipping_status'] ==0){
            $order['status_str'] = '待发货';
        }elseif($order['shipping_status'] ==1 && $order['order_status'] ==1 && $order['pay_status'] ==1){
            $order['status_str'] = '待收货';
            $button .= "<span data-url='".Url('Order/delivery',['order_id'=>$order['order_id']])."'>确认收货</span>";
            $button .= "<span data-url='".Url('Order/kuaidi',['order_id'=>$order['order_id']])."'>查看物流</span>";
        }elseif($order['order_status'] == 2){
            $order['status_str'] = '待评价';
            $button .= "<span data-url='".Url('Order/comment',['order_id'=>$order['order_id']])."'>去评价</span>";
            $button .= "<span data-url='".Url('Order/kuaidi',['order_id'=>$order['order_id']])."'>查看物流</span>";
        }elseif($order['order_status'] == 3){
            $order['status_str'] = '已取消';
        }elseif($order['order_status'] == 4){
            $order['status_str'] = '已完成';
            $button .= "<span data-url='".Url('Order/kuaidi',['order_id'=>$order['order_id']])."'>查看物流</span>";
        }

        $order['button'] = $button;
        $order['goodsList'] = db('OrderGoods')->alias('og')
            ->join('__GOODS__ g','g.id = og.goods_id','LEFT')
            ->join('__ORDER_AFTERSALE__ oa','oa.order_goods_id = og.id','LEFT')
            ->where(['og.order_id'=>$order_id])
            ->field('og.*,g.image,oa.id as aftersale_id')
            ->select();
        $this->assign([
            'order' => $order,
        ]);
        return $this->fetch('orderDetail');

    }

    public function qiandao(){
        $user_info = db("user")->where(array("id"=>$this->user_id))->find();
        $today_str = date('Y-m-d');
        $yesterday = date('Y-m-d',strtotime('-1 day'));
        if($user_info['last_sign_time'] != $yesterday && $user_info['last_sign_time'] != $today_str){
            db('User')->where(['id'=>$this->user_id])->update(['continuous_sign_num'=>0]);
            $user_info['continuous_sign_num'] = 0;
        }
        if(IS_AJAX){
            if($user_info['last_sign_time'] == $today_str){
                $this->ajaxReturn(-1);
            }
            if(db('User')->where(['id'=>$this->user_id])->update(['last_sign_time'=>$today_str,'continuous_sign_num'=>$user_info['continuous_sign_num']+1])) {
                $add_integral = $user_info['continuous_sign_num']+1 >= 7 ? 5 : 1 ;
                accountHandle($user_info,0,$add_integral,'签到获得积分');
                $this->ajaxReturn($add_integral);
            }
            $this->ajaxReturn(-1);
        }
        $html= '';
        for($i = 1;$i<=7;$i++){
            if($i == 7){
                $str = '7天及以上';
                $integral = 5;
            }else{
                $str = $i;
                $integral = 1;
            }
            $flag = '';
            $color = '';
            if($user_info['continuous_sign_num'] >= $i){
                $flag = 'numberday_this';
                $color = '<div class="number_img"><img src="'.C('TMPL_PARSE_STRING')['__HOMEIMG__'].'/day_09.png" alt="" width="100%"></div>';
            }
            $html .= <<<EOF
        <li>
            <div class="number {$flag}">+{$integral} {$color}</div>
            <p class="day">{$str}天</p>
        </li>
EOF;
        }
        $this->assign([
            'user_info' => $user_info,
            'html' => $html,
            'today_str'=>$today_str,
        ]);
        return $this->fetch('qiandao');
    }

}